<template>
    <div class="add-address">
        <ul class="edit-list">
            <li>
                <div class="gather-way-tap displayFlex flexCenter width-full positionR">
                    <span @click="$router.go(-1)">
                        <span class="iconfont icon-arrows_left back"></span>
                    </span>
                    <span class="flex1 text-center edit-title">
                        填写联系信息
                    </span>
                    <span @click="deleteSendWay" v-if="selectedId">
                        <img class="delet-icon" src="../../assets/images/order/delet_icon.png" alt="">
                    </span>
                </div>
            </li>
            <li class="user-data-item displayFlex" >
                <span class="user-data-left displayFlex flexCenter">联系人</span>
                <span class="user-data-right displayFlex flexCenter">
                    <input class="input-style" type="text" placeholder="请输入真实姓名" v-model="addMsg.name">
                </span>
            </li>
            <li class="user-data-item displayFlex" >
                <span class="user-data-left displayFlex flexCenter">手机号</span>
                <span class="user-data-right displayFlex flexCenter">
                    <phone-check
                            :phoneNumProps="addMsg.phone"
                            :porpsContent="phoneContent"
                            @changeCheck="phoneCheckFn"></phone-check>
                </span>
            </li>
            <li class="user-data-item displayFlex" v-if="selectedType == 1">
                <span class="user-data-left displayFlex flexCenter">详细地址</span>
                <span class="user-data-right displayFlex flexCenter">
                    <input class="input-style" type="text" placeholder="请填写详细地址" v-model="addMsg.address">
                </span>
            </li>
            <li class="user-data-item displayFlex justifyCtBwt" >
                <span class="user-data-left displayFlex flexCenter">设为默认</span>
                <span class="user-data-right displayFlex flexCenter">
                    <on-off :isOnProp="addMsg.defaultOne" @changeSelect="changeDefault"></on-off>
                </span>
            </li>
        </ul>
        <div class="displayFlex flexCenter">
            <button class="detail-btn add-btn" @click="isCanCommit" v-if="!selectedId">+新增联系人信息</button>
            <button class="detail-btn add-btn" @click="isCanCommit" v-else>确认</button>
        </div>
    </div>
</template>

<script>
    import { MessageBox } from 'mint-ui';
    export default {
        name: "AddAdress",
        data(){
            return{
                selectedId:0,
                selectedType:0,
                adressType:'edit',
                // sendWay:{
                // "curDeliveryType": 0,            //----------当前配送类型  0：自提   1：快递
                // "supportExpress": false,         //----------是否支持快递，否的话，快递菜单栏置灰
                // "pickupPersons": [{               //----------自提取货人列表
                //     "id":45,                     //-------配送ID
                //     "name":"启明",               //-------取货人名字
                //     "phone":"15919467391",       //-------取货人手机号码
                //     "defaultOne":true,           //-------是否默认
                //     "selected":true              //-------是否当前选择
                // }],
                // "receivePersons": [{                 //----------快递收货人列表
                //     "id":45,                        //-------配送ID
                //     "name":"启明",                  //-------收货人名字
                //     "phone":"15919467391",          //-------收货人手机号码
                //     "address":"田贝三路明阳酒店",  //-------收货地址
                //     "defaultOne":true,              //-------是否默认
                //     "selected":true                 //-------是否当前选择
                // }]
                // },
                addMsg:{
                    name:'',//用户名
                    phone:'',//电话
                    address:'',//地址
                    defaultOne:false,//是否为默认的
                    phoneTrue:false,//手机号码是否符合规范
                },
                phoneContent:{
                    isShowRedWarn:false,
                    closeContent:false,
                }
            }
        },
        created(){
            /*selectedId存在表示修改，否则是添加配送方式*/
            this.selectedId = this.$route.query && this.$route.query.selectedId ? this.$route.query.selectedId : 0;
            /*selectedType 0自提，1快递*/
            this.selectedType = this.$route.query && this.$route.query.selectedType ? this.$route.query.selectedType : 0;
        },
        mounted(){
            this.initAddMsg();
        },
        computed:{
            sendWay(){
                return this.$store.getters.getSendWayMsg
            }
        },
        methods:{
            initAddMsg(){
                let that = this;
                if(this.selectedId){
                    for(let value in that.sendWay){
                        if(value == 'receivePersons' && Array.isArray(that.sendWay.receivePersons) && that.sendWay.receivePersons.length > 0){
                            that.sendWay.receivePersons.forEach((value,receivePersonsIndex)=>{
                                if(value.id == that.selectedId){
                                    that.addMsg = Object.assign({},that.addMsg,value);
                                }
                            })
                        }else if(value == 'pickupPersons' && Array.isArray(that.sendWay.pickupPersons) && that.sendWay.pickupPersons.length > 0){
                            that.sendWay.pickupPersons.forEach((value,pickupPersonsIndex)=>{
                                if(value.id == that.selectedId){
                                    if(value.id == that.selectedId){
                                        that.addMsg = Object.assign({},that.addMsg,value);
                                    }
                                }
                            })
                        }
                    }
                }
            },
            /*删除联系人*/
            deleteSendWay(){
                let that = this;
                MessageBox({
                    title: '',
                    message: '确定删除此联系人',
                    showCancelButton: true,
                    confirmButtonText:'确定',
                    cancelButtonText:'取消',
                }).then((data)=>{
                    if(data == 'confirm'){
                        let url = `${this.NW_API_API_LOCALE_VERSION}/delivery/user/${this.userId}/delete?type=${that.sendWay.curDeliveryType}&id=${that.selectedId}`;
                        this.xurl.deleteLoading(url).then(data => {
                            if (data.success) {
                                this.$root.$emit('toast',{msg:'删除成功'})
                                /*删除之后要重新刷新vuex中的数据*/
                                that.refreshSendWay(that.selectedId);
                            }else if(data.errMsg){
                                this.$root.$emit('toast',{msg:data.errMsg})
                            }else{
                                this.$root.$emit('toast',{msg:'删除失败'})
                            }
                        })
                    }
                })
            },
            /*删除之后刷新联系人列表*/
            refreshSendWay(selectedId){
                let that = this;
                for(let value in that.sendWay){
                    if(value == 'receivePersons' && Array.isArray(that.sendWay.receivePersons) && that.sendWay.receivePersons.length > 0){
                        that.sendWay.receivePersons.forEach((value,receivePersonsIndex)=>{
                            if(value.id == selectedId){
                                /*如果删除的是选中的，那就让列表中第一个选中,不能让默认的选中，因为用户有可能删除的就是默认的*/
                                if(value.selected){
                                    that.sendWay.receivePersons[0].selected = true;
                                }
                                that.sendWay.receivePersons.splice(receivePersonsIndex,1);
                            }
                        })
                    }else if(value == 'pickupPersons' && Array.isArray(that.sendWay.pickupPersons) && that.sendWay.pickupPersons.length > 0){
                        that.sendWay.pickupPersons.forEach((value,pickupPersonsIndex)=>{
                            if(value.id == selectedId){
                                /*如果删除的是选中的，那就让列表中第一个选中,不能让默认的选中，因为用户有可能删除的就是默认的*/
                                if(value.selected){
                                    that.sendWay.pickupPersons[0].selected = true;
                                }
                                that.sendWay.pickupPersons.splice(pickupPersonsIndex,1);
                            }
                        })
                    }
                }
                /*改变vuex中的数据*/
                this.$store.commit('editSendWay',that.sendWay);
                /*返回到之前的页面*/
                this.$router.go(-1);
                // this.receivePersons
            },
            /*修改默认状态*/
            changeDefault(val){
                this.addMsg.defaultOne = val
            },
            /*手机号码改变的时候*/
            phoneCheckFn(val){
                this.addMsg.phone = val.phoneNum;
                this.addMsg.phoneTrue = val.phoneTrue;
            },
            /*是否可以提交*/
            isCanCommit(){
                if(this.addMsg.phoneTrue && this.addMsg.name){
                    if(this.selectedType == 1){
                        if(this.addMsg.address){
                            this.commitAddress()
                        }else{
                            this.$root.$emit('toast',{msg:'请填写收货地址'})
                        }
                    }else{
                        this.commitAddress()
                    }
                }
            },
            /*提交地址*/
            commitAddress(){
                /*selected 存在表示是修改，不存在表示是新建*/
                let url = "";
                let that = this;
                let text = '';
                let params = {
                    "deliveryType":that.selectedType,             //-------配送类型  0：自提   1：快递
                    "name":that.addMsg.name,                //-------姓名
                    "phone":that.addMsg.phone,                  //-------手机号码
                    "address":that.addMsg.address,              //-------地址，自提则不传
                    "setDefault":that.addMsg.defaultOne,        //-------是否设为默认
                };
                if(this.selectedId){
                    let tempObj = {
                        "deliveryId":that.selectedId,               //-------配送ID
                    };
                    params = Object.assign({},params,tempObj);
                    url = `${this.NW_API_API_LOCALE_VERSION}/delivery/user/${this.userId}/update`;
                    text = '修改'
                }else{
                    url = `${this.NW_API_API_LOCALE_VERSION}/delivery/user/${this.userId}/add`;
                    text = '添加'
                }
                this.xurl.postDataJsonLoading(url,params).then(data => {
                    if (data.success) {
                        this.$root.$emit('toast',{msg:text+"联系人成功"})
                        /*删除之后要重新刷新vuex中的数据*/
                        that.refreshStoreSendWay(that.selectedId);
                    }else if(data.errMsg){
                        this.$root.$emit('toast',{msg:data.errMsg});
                    }else{
                        this.$root.$emit('toast',{msg:text+"联系人失败"});
                    }
                })
            },
            /*刷新配送方式列表*/
            refreshStoreSendWay(){
                let that = this;
                /*添加数据的话不能前端做数据处理了，必须要从后端拿到数据*/
                /*sendWay*/
                let sendWayObj = {
                    "userId":this.userId,        //----------用户ID
                    "supportExpress":that.addMsg.supportExpress,      //--------是否全部店铺支持快递
                    "curDeliveryType":that.sendWay.curDeliveryType,         //--------当前配送类型  0：自提   1：快递
                    "curDeliveryId":that.addMsg.curDeliveryId           //--------当前配送ID
                }
                let url = `${this.NW_API_API_LOCALE_VERSION}/delivery/user/procure/get`;
                this.xurl.postDataJsonLoading(url,sendWayObj).then(data => {
                    if (data.success) {
                        this.$store.commit('editSendWay',data.result);
                        this.$router.go(-1);
                    }else if(data.errMsg){
                        this.$root.$emit('toast',{msg:data.errMsg});
                    }else{
                        this.$root.$emit('toast',{msg:'获取联系人地址信息错误，请重新获取'});
                    }
                })
            }
        },
        watch:{
            addMsg:{
                handler(value,oldValue){
                },
                immediate:true,
                deep:true
            }
        },
        components:{
            'on-off': () => import('../../components/commonComponents/onOff/OnOff'),
            'phone-check': () => import('../../components/commonComponents/phone/PhoneCheck'),
        }
    }
</script>

<style scoped lang="scss">
    .add-address /deep/ {
        .phone-input{
            border: none;
            margin-top: 0;
            padding-left: 0;
            line-height: .4rem;
        }
    }
    .user-data-item {
        padding: .15rem;
        border-bottom: 1px solid #f1f1f1;
    }
    .detail-btn{
        width: 90%;
        margin-top: .26rem;
        height: .4rem;
        text-align: center;
        line-height: .4rem;
        font-size: .14rem;
        -webkit-border-radius: .25rem;
        -moz-border-radius: .25rem;
        border-radius: .25rem;
        color: #fff;
    }
    .user-data-left{
        color: #333333;
        font-size: .13rem;
        display: inline-block;
        width: .9rem;
        line-height: .4rem;
        height: .4rem;
    }
    .add-btn{
        background-image: linear-gradient(to right,#9EBDFF,#5D89E8);
    }
    .edit-list{
        padding: 0 .15rem;
    }
    .back{
        font-size: .28rem;
        color: #999;
    }
    .delet-icon{
        width: .2rem;
    }
    .gather-way-tap{
        padding: .11rem 0 ;
        border-bottom: 1px solid #F0F0F0;
    }
    .edit-title{
        font-size: .16rem;
        color: #1A1A1A;
    }
    .input-style{
        font-size: .13rem;
        height: .4rem;
        line-height: .4rem;
    }
    .input-style::-webkit-input-placeholder{
        color: #CCCCCC;
    }
    .input-style::placeholder{
        color: #CCCCCC;
    }
</style>